#include<muduo/net/TcpServer.h>
#include<muduo/base/Logging.h>
#include<muduo/net/EventLoop.h>
#include<muduo/base/Timestamp.h>
#include<iostream>
#include<unistd.h>
#include<stdlib.h>
using muduo::net::EventLoop;
using muduo::net::InetAddress;
using muduo::net::TcpConnectionPtr;
using muduo::net::Buffer;
using muduo::Timestamp;
using muduo::net::TcpServer;
using std::placeholders::_1;
using std::placeholders::_2;
using std::placeholders::_3;

class EchoServer{
	public:
		EchoServer(EventLoop* loop, const InetAddress& listenAddr);
		void start();
	private:
		void onConnection(const TcpConnectionPtr& conn);
		void onMessage(const TcpConnectionPtr& conn, Buffer* buf, Timestamp time);
		EventLoop* loop_;
		TcpServer server_;

};
void EchoServer::start(){
	server_.start();
}
EchoServer::EchoServer(EventLoop* loop,const InetAddress& listenAddr):loop_(loop),server_(loop, listenAddr, "mqd_echo"){
	server_.setConnectionCallback(std::bind(&EchoServer::onConnection, this, _1));
	server_.setMessageCallback(std::bind(&EchoServer::onMessage, this, _1, _2, _3));
}	

void EchoServer::onConnection(const TcpConnectionPtr& conn){
	std::cout<<conn->peerAddress().toIpPort()<<" -> "<<(conn->connected() ? "UP": "DOWN")<<std::endl;
}
void EchoServer::onMessage(const TcpConnectionPtr& conn, Buffer* buf, Timestamp time){
	std::string msg(buf->retrieveAllAsString());
	std::cout<< conn->name() << "echo "<< msg.size()<< " bytes, "<< "data received at " << time.toString()<<std::endl;
	conn->send(msg);
}
int main(int argc, char**argv){
	int port = atoi(argv[1]);
	std::cout<< "pid = " << getpid() <<std::endl;
	EventLoop loop;
	InetAddress listenAddr(port);
	EchoServer mqd_server(&loop, listenAddr);
	mqd_server.start();
	loop.loop();
}
